import json
import os
import re
from datetime import datetime

from flask import Flask
from flask_cors import CORS

from compoent.img.imgwithmedia.ImageToVideo import ImageToVideo
from compoent.medias.videos.AudioExtractor import AudioExtractor
from compoent.medias.videos.FrameExtractor import FrameExtractor
from compoent.medias.videos.VideoSplitter import VideoSplitter
from compoent.text.book.lines.BlockSorter import BlockSorter
from tools.createRes import DynamicDataBuilder
from tools.mangejsondata import myjson
from tools.notejson import NoteJsonEditor
from tools.resenum import FieldType
from compoent.text.book.lines.LineSpacer import LineSpacer
from compoent.text.book.lines.TextProcessor import TextProcessor
from compoent.text.book.lines.UnitProcessor import UnitProcessor
from compoent.text.book.lines.DropEmptyLine import DropEmptyLine
from compoent.text.book.lines.TextClearAI import TextClearAI
from compoent.text.book.lines.EmptyLineToOne import EmptyLineToOne
from compoent.text.book.lines.JapaneseWordSorter import JapaneseWordSorter
from compoent.text.textwithmedia.TxtToImg import TxtToImg
from compoent.medias.audios.AudioSplitter import AudioSplitter
from compoent.medias.audios.AudioRenamer import AudioRenamer
from compoent.pdf.PDFToImageConverter import PDFToImageConverter
from compoent.img.ImageFormatConverter import ImageFormatConverter
from compoent.img.ImageOpacityAdjuster import ImageOpacityAdjuster
from compoent.img.imgwithmedia.ImageToPDFConverter import ImageToPDFConverter
from compoent.file.FileRenamer import FileRenamer

app = Flask(__name__)
# CORS(app, resources={
#     r"/api/*": {
#         "origins": ["http://localhost:5173", "http://127.0.0.1:5173"],
#         "methods": ["GET", "POST", "OPTIONS"],
#         "allow_headers": ["Content-Type", "Authorization"]
#     }
# })
CORS(app)

# 配置
UPLOAD_FOLDER = os.path.expanduser('~/Desktop/form_uploads')  # 桌面上的上传文件夹
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx'}
# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


# CORS(app, resources={r"/api/*": {"origins": "*"}})
# 或者更严格：
# CORS(app, resources={r"/api/*": {"origins": "http://localhost:5173"}})

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/api/test', methods=['GET'])
def test():
    res = DynamicDataBuilder()
    res.add("姓名", FieldType.TEXT.value, "12")
    return res.build()


@app.route('/api/text/LineSpacer', methods=['POST'])
def LineSpacer2():
    x = 0
    textdata = ""
    for key in request.form:
        if key == "LineSpacerLines":
            x = int(request.form.get(key))
        if key == "LineSpacerData":
            textdata = request.form.get(key)
    obj = LineSpacer(x)
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.process_text(textdata))
    print(textdata)
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/img/ImageFormatConverter', methods=['POST'])
def ImageFormatConverter2():
    obj = ImageFormatConverter(request.form.get("input_dir"))
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_dir(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("fmt") and form.get("fmt").strip():
        try:
            obj.set_fmt(form.get("fmt"))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.convert_images())
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/audio/AudioRenamer', methods=['POST'])
def AudioRenamer2():
    obj = AudioRenamer()
    form = request.form
    if form.get("audio_dir") and form.get("audio_dir").strip():
        try:
            obj.set_audio_dir(form.get("audio_dir"))
        except ValueError:
            pass

    if form.get("text") and form.get("text").strip():
            try:
                obj.set_text(form.get("text"))
            except ValueError:
                pass
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, "\n".join(obj.rename_audio_files()))
    return jsonify({"response_data": res.build()}), 200




def fix_json_string(json_str):
    """尝试修复常见的JSON格式错误"""
    if not json_str:
        return json_str

    # 修复1: 将单引号转换为双引号（但要避免转换内容中的单引号）
    # 简单的修复：将外层的单引号转换为双引号
    fixed = json_str

    # 修复没有引号的属性名
    fixed = re.sub(r'(\w+):', r'"\1":', fixed)

    # 将单引号字符串转换为双引号字符串
    # 但要注意不要转换字符串内容中的单引号
    fixed = re.sub(r"'([^']*)'", r'"\1"', fixed)

    return fixed

@app.route('/api/video/VideoSplitter', methods=['POST'])
def VideoSplitter2():
    obj = VideoSplitter()
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_dir(form.get("output_dir"))
        except ValueError:
            pass
    if form.get("input_dir") and form.get("input_dir").strip():
        try:
            obj.set_input_path(form.get("input_dir"))
        except ValueError:
            pass

    if form.get("fmt") and form.get("fmt").strip():
        try:
            obj.set_output_format(form.get("fmt"))
        except ValueError:
            pass

    if form.get("time_points") and form.get("time_points").strip():
        try:
            obj.set_time_points(json.loads(form.get("time_points")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, "\n".join(obj.split()))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/video/FrameExtractor', methods=['POST'])
def FrameExtractor2():
    form = request.form
    obj = FrameExtractor(form.get("input_path"))

    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_folder(form.get("output_dir"))
        except ValueError:
            pass
    if form.get("mode") and form.get("mode").strip():
        try:
            obj.set_mode(form.get("mode"))
        except ValueError:
            pass
    if form.get("interval") and form.get("interval").strip():
        try:
            if form.get("mode")=="frame":
                obj.set_frame_interval(int(form.get("interval")))
            else:
                obj.set_interval(float(form.get("interval")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value,obj.extract())
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/file/FileRenamer', methods=['POST'])
def FileRenamer2():
    form = request.form
    obj = FileRenamer(form.get("input_dir"))

    if form.get("position") and form.get("position").strip():
        try:
            obj.set_position(form.get("position"))
        except ValueError:
            pass

    if form.get("keepname") and form.get("keepname").strip():
        try:
            print("keepname:"+form.get("keepname"))
            obj.set_keep_original_name(form.get("keepname").lower()=="true")
            print("objkeepname:"+str(obj.keep_original_name))
        except ValueError:
            pass

    if form.get("start") and form.get("start").strip():
        try:
            obj.set_start_number(int(form.get("start")))
        except ValueError:
            pass

    if form.get("padding") and form.get("padding").strip():
        try:
            obj.set_padding(int(form.get("padding")))
        except ValueError:
            pass
    if form.get("preffix") and form.get("preffix").strip():
        try:
            print("设置前缀"+form.get("preffix"))
            obj.set_prefix(form.get("preffix"))
        except ValueError:
            pass
    if form.get("suffix") and form.get("suffix").strip():
        try:
            obj.set_suffix(form.get("suffix"))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, "\n".join(obj.rename_files()))
    return jsonify({"response_data": res.build()}), 200

@app.route('/api/notes', methods=['POST'])
def receive_notes():
    note=NoteJsonEditor()
    data = request.get_json()
    print("收到前端数据：", data)
    json_str = json.dumps(data, ensure_ascii=False)
    note.replace_item_text(json.loads(json_str)["items"])
    note.save_json()
    print("json标准化dumps收到前端数据：", json_str)
    return note.getnotejsn()

@app.route('/api/notes/get', methods=['POST'])
def get_notes():
    note=NoteJsonEditor()
    return  note.getnotejsn()

@app.route('/api/img/ImageOpacityAdjuster', methods=['POST'])
def ImageOpacityAdjuster2():
    obj = ImageOpacityAdjuster(request.form.get("input"))
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_dir(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("opacity") and form.get("opacity").strip():
        try:
            obj.set_opacity(float(form.get("opacity")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.adjust_opacity())
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/img/ImageOpacityAdjuster2', methods=['POST'])
def ImageOpacityAdjuster3():
    obj = ImageOpacityAdjuster(request.form.get("input"))
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_dir(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("opacity") and form.get("opacity").strip():
        try:
            obj.set_opacity(float(form.get("opacity")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.adjust_opacity2())
    return jsonify({"response_data": res.build()}), 200

@app.route('/api/img/ImageToVideo', methods=['POST'])
def ImageToVideo2():
    obj = ImageToVideo()
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_folder(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("input_dir") and form.get("input_dir").strip():
        try:
            obj.set_input_folder(form.get("input_dir"))
        except ValueError:
            pass

    if form.get("frame_time") and form.get("frame_time").strip():
        try:
            obj.set_frame_time(float(form.get("frame_time")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.make_video())
    return jsonify({"response_data": res.build()}), 200

@app.route('/api/img/ImageToPDFConverter', methods=['POST'])
def ImageToPDFConverter2():
    obj = ImageToPDFConverter(request.form.get("input"))
    form = request.form
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_dir(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("outputfilename") and form.get("outputfilename").strip():
        try:
            obj.set_output_name(form.get("outputfilename"))
        except ValueError:
            pass
    if form.get("width_cm") and form.get("width_cm").strip():
        try:
            obj.set_width_cm(float(form.get("width_cm")))
        except ValueError:
            pass
    if form.get("height_cm") and form.get("height_cm").strip():
        try:
            obj.set_height_cm(float(form.get("height_cm")))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.convert_to_pdf_with_size())
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/pdf/PDFToImageConverter', methods=['POST'])
def PDFToImageConverter2():
    dpi = 200
    pdf_path = ""
    fmt = "PNG"
    output_path = r"C:\Users\33720\Desktop\temp"
    if request.form.get("dpi") and request.form.get("dpi").strip():
        try:
            dpi = int(request.form.get("dpi"))
        except ValueError:
            pass
    if request.form.get("pdf_path") and request.form.get("pdf_path").strip():
        pdf_path = request.form.get("pdf_path")
    if request.form.get("output_path") and request.form.get("output_path").strip():
        output_path = request.form.get("output_path")

    if request.form.get("fmt") and request.form.get("fmt").strip():
        fmt = request.form.get("fmt")

    obj = PDFToImageConverter()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, "\n".join(obj.convert_pdf_to_images(pdf_path, output_path, dpi, fmt)))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/JapaneseWordSorter', methods=['POST'])
def JapaneseWordSorter2():
    x = 0
    textdata = ""
    for key in request.form:
        if key == "LineSpacerLines":
            x = int(request.form.get(key))
        if key == "textdata":
            textdata = request.form.get(key)
    obj = JapaneseWordSorter()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.sort_and_print(textdata))
    print(textdata)
    return jsonify({"response_data": res.build()}), 200

@app.route('/api/video/AudioExtractor', methods=['POST'])
def AudioExtractor2():
    form=request.form
    obj = AudioExtractor(form.get("input_dir"))
    if form.get("output_dir") and form.get("output_dir").strip():
        try:
            obj.set_output_folder(form.get("output_dir"))
        except ValueError:
            pass

    if form.get("fmt") and form.get("fmt").strip():
            try:
                obj.set_output_format(form.get("fmt"))
            except ValueError:
                pass

    if form.get("bitrate") and form.get("bitrate").strip():
            try:
                obj.set_bitrate(form.get("bitrate"))
            except ValueError:
                pass

    if form.get("sample_rate") and form.get("sample_rate").strip():
            try:
                obj.set_sample_rate( int(form.get("sample_rate")))
            except ValueError:
                pass


    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, "\n".join(obj.extract_audio()))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/JapaneseWordSorter/remove_duplicate_lines', methods=['POST'])
def JapaneseWordSorter3():
    x = 0
    textdata = ""
    for key in request.form:
        if key == "LineSpacerLines":
            x = int(request.form.get(key))
        if key == "textdata":
            textdata = request.form.get(key)
    obj = JapaneseWordSorter()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.remove_duplicate_lines_preserve_all(textdata))
    print(textdata)
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/JapaneseWordSorter/sort_by_first_part_length', methods=['POST'])
def JapaneseWordSorter4():
    x = 0
    textdata = ""
    for key in request.form:
        if key == "LineSpacerLines":
            x = int(request.form.get(key))
        if key == "textdata":
            textdata = request.form.get(key)
    obj = JapaneseWordSorter()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.sort_by_first_part_length(textdata))
    print(textdata)
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/audio/AudioSplitter', methods=['POST'])
def AudioSplitter2():
    resobj = request.form
    obj = AudioSplitter()
    obj.set_input_path(resobj.get("inputpath"))
    if resobj.get("outputpath") and resobj.get("outputpath").strip():
        try:
            obj.set_output_dir(resobj.get("outputpath"))
        except ValueError:
            pass
    if resobj.get("fmt") and resobj.get("fmt").strip():
        try:
            obj.set_fmt(resobj.get("fmt"))
        except ValueError:
            pass

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.split_audio(json.loads(resobj.get("timelist"))))
    return jsonify({"response_data": res.build()}), 200
@app.route('/api/text/BlockSorter', methods=['POST'])
def BlockSorter2():
    resobj = request.form


    reverse=False
    if resobj.get("text") is None:
        return ""
    if resobj.get("reverse") and resobj.get("reverse").strip():
        try:
            ism=resobj.get("reverse")
            print(f"resobj.get：reverse：{ism}")
            reverse = True if resobj.get("reverse").lower() == "true" else False
        except ValueError:
            pass
    print(f"{reverse}")
    obj = BlockSorter(resobj.get("text"),reverse)
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.process_and_copy())
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/TextProcessor', methods=['POST'])
def TextProcessor2():
    form = request.form

    # 使用 form.get() 获取参数，并直接传入类构造函数（类内会自动处理 None 和类型）
    obj = TextProcessor(
        n=form.get("n"),
        m=form.get("m"),
        x=form.get("x"),
        y=form.get("y"),
        z=form.get("z"),
        o=form.get("o")
    )

    text_data = form.get("textdata") or ""
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.process_text(text_data))

    print("接收到的文本内容:", text_data)
    return jsonify({"response_data": res.build()}), 200



@app.route('/api/text/TxtToImg', methods=['POST'])
def TxtToImg2():
    form = request.form

    obj = TxtToImg()
    # 使用条件表达式简化代码
    if form.get("width") and form.get("width").strip():
        try:
            obj.set_default_width(int(form.get("width")))
        except ValueError:
            pass  # 忽略转换错误
    if form.get("height") and form.get("height").strip():
        try:
            obj.set_default_height(int(form.get("height")))
        except ValueError:
            pass
    if form.get("font_size") and form.get("font_size").strip():
        try:
            obj.set_default_font_size(int(form.get("font_size")))
        except ValueError:
            pass

    if form.get("starty") and form.get("starty").strip():
            try:
                obj.set_starty(int(form.get("starty")))
            except ValueError:
                pass

    if form.get("leftx") and form.get("leftx").strip():
            try:
                obj.set_leftx(int(form.get("leftx")))
            except ValueError:
                pass

    if form.get("lines_per_image") and form.get("lines_per_image").strip():
        try:
            obj.set_lines_per_image(int(form.get("lines_per_image")))
        except ValueError:
            pass

    if form.get("output_dir") and form.get("output_dir").strip():
        obj.set_default_output_dir(form.get("output_dir").strip())
    print(obj.to_str())

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, str(obj.generate_images(form.get("textdata"))))

    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/TxtToImgBackground', methods=['POST'])
def TxtToImg3():
    form = request.form

    obj = TxtToImg()
    # 使用条件表达式简化代码
    if form.get("width") and form.get("width").strip():
        try:
            obj.set_default_width(int(form.get("width")))
        except ValueError:
            pass  # 忽略转换错误
    if form.get("height") and form.get("height").strip():
        try:
            obj.set_default_height(int(form.get("height")))
        except ValueError:
            pass
    if form.get("font_size") and form.get("font_size").strip():
        try:
            obj.set_default_font_size(int(form.get("font_size")))
        except ValueError:
            pass
    if form.get("starty") and form.get("starty").strip():
        try:
            obj.set_starty(int(form.get("starty")))
        except ValueError:
            pass

    if form.get("leftx") and form.get("leftx").strip():
        try:
            obj.set_leftx(int(form.get("leftx")))
        except ValueError:
            pass

    if form.get("lines_per_image") and form.get("lines_per_image").strip():
        try:
            obj.set_lines_per_image(int(form.get("lines_per_image")))
        except ValueError:
            pass
    if form.get("bgimg") and form.get("bgimg").strip():
        print("getBack:" + form.get("bgimg"))
        try:
            obj.set_bgimg(form.get("bgimg"))
        except ValueError:
            pass

    if form.get("output_dir") and form.get("output_dir").strip():
        obj.set_default_output_dir(form.get("output_dir").strip())
    print(obj.to_str())

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, str(obj.generate_images_backgroud(form.get("textdata"))))

    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/EmptyLineToOne', methods=['POST'])
def EmptyLineToOne2():
    form = request.form
    obj = EmptyLineToOne()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.remove_extra_empty_lines(form.get("textdata")))
    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/TextClearAI', methods=['POST'])
def TextClearAI2():
    form = request.form
    obj = TextClearAI()
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.remove_special_chars(form.get("textdata")))
    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/DropEmptyLine', methods=['POST'])
def DropEmptyLine2():
    form = request.form
    obj = DropEmptyLine()

    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.read_and_process_input(form.get("textdata")))
    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/text/UnitProcessor', methods=['POST'])
def UnitProcessor2():
    form = request.form
    obj = UnitProcessor(int(form.get("n")), int(form.get("m")), form.get("action"))
    res = DynamicDataBuilder()
    res.add("Result", FieldType.TEXTAREA.value, obj.process_lines(form.get("textdata")))
    print(form.get("tetxdata"))
    return jsonify({"response_data": res.build()}), 200


@app.route('/api/json/get_user_config_by_name', methods=['POST'])
def get_user_config_by_nameapi():
    form = request.form
    x = form.get("configName")
    print("configName:" + form.get("configName"))
    obj = myjson().get_user_config_by_name(x)

    resdata = obj
    res = DynamicDataBuilder()
    if resdata is None:
        res.add("jsonData", FieldType.TEXTAREA.value, "None")
        re = res.build()
        return jsonify({"response_data": re}), 200
    res.add("jsonData", FieldType.TEXTAREA.value, obj)
    re = res.build()
    print(re)
    return jsonify({"response_data": re}), 200


def save_file_to_desktop(file, filekey, index=0):
    print("=" * 20)
    print("上传文件名：" + filekey)
    """保存文件到桌面，并返回文件信息"""
    try:
        print(f"    🚀 开始保存文件: {file.filename}")

        if not file or not file.filename:
            print("    ❌ 文件对象或文件名为空")
            return None

        # 检查文件内容
        current_pos = file.tell()
        file.seek(0)
        file_data = file.read()
        file.seek(current_pos)  # 恢复指针位置

        if len(file_data) == 0:
            print("    ❌ 文件内容为空")
            return None

        # 生成唯一的文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        original_name = file.filename
        name, ext = os.path.splitext(original_name)

        # 检查重名文件并递增索引
        while True:
            new_filename = f"{name}_{index}{ext}"
            file_path = os.path.join(UPLOAD_FOLDER, new_filename)

            # 如果文件不存在，跳出循环
            if not os.path.exists(file_path):
                break
            # 如果文件已存在，递增索引
            index += 1
            print(f"    ⚠️ 文件已存在，尝试索引: {index}")
        print(f"    ✅ 最终文件名: {new_filename}")
        # 保存文件
        file.save(file_path)
        print(f"    ✅ 文件保存成功: {file_path}")

        return {
            "original_name": original_name,
            "saved_name": new_filename,
            "file_path": file_path,
            "file_size": len(file_data)
        }


    except Exception as e:
        print(f"    ❌ 保存文件时出错: {str(e)}")
        return None

        print(f"    📁 保存路径: {file_path}")

        # 确保目录存在
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        # 保存文件
        file.save(file_path)

        # 验证文件是否真的保存了
        if os.path.exists(file_path):
            file_size = os.path.getsize(file_path)
            print(f"    ✅ 文件保存成功! 大小: {file_size} bytes")

            return {
                "original_name": original_name,
                "saved_name": new_filename,
                "saved_path": file_path,
                "field_name": field_name,
                "size": file_size
            }

        else:
            print("    ❌ 文件保存后不存在!")
            return None

    except Exception as e:
        print(f"    💥 保存文件时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return None


@app.route('/api/submit-form', methods=['POST'])
def handle_form_submission():
    """处理表单提交"""
    try:
        print("=" * 50)
        print("submit-form收到表单提交请求")
        print("=" * 50)

        # 存储所有数据
        form_data = {}
        uploaded_files = []

        # 处理普通表单字段
        for key in request.form:
            form_data[key] = request.form.get(key)
            print(f"普通字段 - {key}: {request.form.get(key)}")

        for key in request.files:
            files = request.files.getlist(key)
            print(f"文件字段 - {key}: 找到 {len(files)} 个文件")

            file_infos = []
            for i, file in enumerate(files):
                print(f"  文件 {i + 1} 详细信息:")
                print(f"    文件名: '{file.filename}'")
                print(f"    内容类型: '{file.content_type}'")

                # 检查文件内容
                file_data = file.read()
                print(f"    文件大小: {len(file_data)} bytes")
                file.seek(0)  # 重置文件指针

                # 检查文件对象属性
                print(f"    是否有文件名: {bool(file.filename)}")
                print(f"    文件对象类型: {type(file)}")

                if file.filename and len(file_data) > 0:  # 确保文件不为空且有内容
                    print(f"    ✅ 文件有效，尝试保存...")
                    file_info = save_file_to_desktop(file, key, i)
                    if file_info:
                        file_infos.append(file_info)
                        uploaded_files.append(file_info)
                        print(f"    ✅ 保存成功: {file.filename} -> {file_info['saved_name']}")
                    else:
                        print(f"    ❌ 保存失败")
                else:
                    print(f"    ❌ 文件无效: 文件名为空或文件内容为空")

                print("    ---")

            form_data[key] = file_infos

        # 输出完整的请求信息
        print("\n请求头信息:")
        for header, value in request.headers:
            if header.lower() in ['content-type', 'content-length', 'user-agent']:
                print(f"  {header}: {value}")

        print(f"\n请求方法: {request.method}")
        print(f"内容类型: {request.content_type}")
        print(f"内容长度: {request.content_length}")

        # 返回响应
        response_data = {
            "success": True,
            "message": "表单提交成功",
            "received_data": form_data,
            "uploaded_files": uploaded_files,
            "total_files": len(uploaded_files),
            "timestamp": datetime.now().isoformat()
        }

        print(f"\n返回响应: {json.dumps(response_data, indent=2, ensure_ascii=False)}")
        print("=" * 50)
        res = DynamicDataBuilder()
        res.add("状态", FieldType.TEXT.value, "True")
        res.add("message", FieldType.TEXT.value, "表单提交成功")
        res.add("uploaded_files", FieldType.TEXTAREA.value, str(uploaded_files))
        # return jsonify(response_data), 200
        return jsonify({"response_data": res.build()}), 200

    except Exception as e:
        error_msg = f"处理表单时发生错误: {str(e)}"
        print(f"错误: {error_msg}")
        return jsonify({
            "success": False,
            "message": error_msg
        }), 500


@app.route('/api/dropline', methods=['POST'])
def dropline1():
    """处理表单提交"""
    try:
        print("=" * 50)
        print("收到表单提交请求")
        print("=" * 50)

        # 存储所有数据
        form_data = {}
        uploaded_files = []

        # 处理普通表单字段
        for key in request.form:
            form_data[key] = request.form.get(key)
            print(f"普通字段 - {key}: {request.form.get(key)}")

        # print(f"\n返回响应: {json.dumps(, indent=2, ensure_ascii=False)}")
        print("=" * 50)

        return jsonify({"response_data": [
            {
                "name": "id",
                "type": "text",
                "data": "123"
            }
        ]
        }), 200
    except Exception as e:
        error_msg = f"处理表单时发生错误: {str(e)}"
        print(f"错误: {error_msg}")
        return jsonify({
            "success": False,
            "message": error_msg
        }), 500


@app.route('/api/jsondata')
def get_data():
    return jsonify(myjson().read())


@app.route('/api/setTree', methods=['POST'])
def set_tree():
    try:
        print("=" * 50)
        print("收到表单提交请求")
        print("=" * 50)

        # 处理普通表单字段
        for key in request.form:
            if key == "treedata":
                re = myjson().set_tree(request.form.get(key))
                if re:
                    print("更新树成功")

                print(f"settree==>{key}==>{request.form.get(key)}")
    except Exception as e:
        print(e)
    return "更新完成"


@app.route('/api/add_user_configer', methods=['POST'])
def add_user_configer():
    try:
        print("=" * 50)
        print("收到表单提交请求")
        print("=" * 50)
        print("add_user_configer")
        # 处理普通表单字段
        for key in request.form:
            if key == "userconfiger":
                myjson().add_user_configer(request.form.get(key))
                print("添加配置成功")
                print(f"add {key}: {request.form.get(key)}")
    except Exception as e:
        print(e)
    return "更新完成"


from flask import request, jsonify


@app.route('/api/remove_user_configer_by_key', methods=['POST'])
def remove_user_configer():
    try:
        print("=" * 50)
        print("收到表单提交请求")
        print("=" * 50)

        userconfiger_key = request.form.get("userconfiger")
        if not userconfiger_key:
            return jsonify({"msg": "缺少 userconfiger 参数"}), 400

        myjson().remove_user_configer_by_key(userconfiger_key)
        print(f"delete userconfiger:{userconfiger_key}")
        return jsonify({"msg": userconfiger_key}), 200
    except Exception as e:
        print(f"删除配置出错: {e}")
        return jsonify({"msg": str(e)}), 500


# @app.route('/api/remove_user_configer_by_key', methods=['POST'])
# def remove_user_configer():
#     try:
#         print("=" * 50)
#         print("收到表单提交请求")
#         print("=" * 50)
#
#         userconfiger_key = request.form.get("userconfiger")
#         if not userconfiger_key:
#             return jsonify({"msg": "缺少 userconfiger 参数"}), 400
#
#         removestatus = myjson().remove_user_configer_by_key(userconfiger_key)
#         print(f"delete userconfiger:{userconfiger_key}")
#
#         if removestatus :
#             print("删除配置成功")
#             return jsonify({"msg": userconfiger_key}), 200
#         else:
#             print(f"删除配置失败: {removestatus}")
#             return jsonify({"msg": removestatus}), 500
#
#     except Exception as e:
#         print(f"删除配置出错: {e}")
#         return jsonify({"msg": str(e)}), 500


@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "upload_folder": UPLOAD_FOLDER,
        "folder_exists": os.path.exists(UPLOAD_FOLDER)
    })


if __name__ == '__main__':
    print(f"服务器启动中...")
    # print(f"文件将保存到: {UPLOAD_FOLDER}")
    # try:
    #     print(myjson().remove_user_configer_by_key("x"))
    # except Exception as e:
    #     print(e)

    app.run(debug=True, host='0.0.0.0', port=5000)
